package tree.递归;

import po.TreeNode;

/**
 * @author songZiHao
 * @version 1.0.0
 * @ClassName N二叉搜索树的最小绝对差530and783.java
 * @Description https://leetcode-cn.com/problems/minimum-absolute-difference-in-bst/
 * https://leetcode-cn.com/problems/minimum-distance-between-bst-nodes/
 * @createTime 2021年06月02日 19:47:00
 */
public class N二叉搜索树的最小绝对差530and783 {
    /*int differ=Integer.MAX_VALUE;
    int pre=-1;
    public int getMinimumDifference(TreeNode root) {
        searchMin(root);
        return differ;
    }

    private void searchMin(TreeNode root) {
        if (root==null){
            return ;
        }
        searchMin(root.left);
        if (pre != -1) {
            differ = Math.min(root.val - pre, differ);
        }
        pre=root.val;
        searchMin(root.right);
    }*/

    Integer mainDiff = Integer.MAX_VALUE;
    //前一个节点的值
    int pre = -1;

    public int minDiffInBST(TreeNode root) {
        //因为是二叉搜索树，所以按照中序遍历的方式，来进行比较每个节点的差值，相邻的两个数之间的最小的差值就一定是整个树最小的差值
        findMin(root);
        return mainDiff;
    }

    private void findMin(TreeNode root) {
        //如果节点为null，返回-1
        if (root == null) {
            return;
        }
        //寻找左节点的值
        findMin(root.left);
        //计算当前节点和父节点的值差，然后比较
        if (pre != -1) {
            mainDiff = Math.min(root.val - pre, mainDiff);
        }
        pre = root.val;
        findMin(root.right);
    }
}
